package 十一树的实际应用;

import java.util.ArrayList;
import java.util.Collections;

/**
 * @Author XuZhuHong
 * @CreateTime 2021/9/27 16:23
 * 赫夫曼树的创建
 */
public class HuffmanTree {
    public static void main(String[] args) {
        int arr[] = {13, 7, 8, 3, 29, 6, 1};
        Node root = createHuffmanTree(arr);
        root.preOrder();
    }

    private static Node createHuffmanTree(int[] arr) {
        ArrayList< Node > nodes = new ArrayList<>();
        for (int i = 0; i < arr.length; i++) {
            nodes.add(new Node(arr[i]));
        }


        while (nodes.size() > 1) {
            //调用java的排序的方法
            Collections.sort(nodes);

            //获取最小的节点  组成新的二叉树
            Node leftNode = nodes.get(0);
            Node rightNode = nodes.get(1);

            //把新的二叉树 又放入数组中
            Node node = new Node(leftNode.getValue() + rightNode.getValue());
            //把他的左右节点分别指向左右节点
            node.setLeft(leftNode);
            node.setRight(rightNode);
            nodes.add(node);

            //移出前面两个节点  为什么不能用0 和1 ？  因为这个数组
            // 当移除了0过后  他就会把后面的数据往前移动  之前的get(1)就等于了移出过后的get(0)
            nodes.remove(leftNode);
            nodes.remove(rightNode);
        }
        return nodes.get(0);
    }
}

class Node implements Comparable< Node > {
    private int value;
    private Node left;
    private Node right;

    public Node(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    public Node getLeft() {
        return left;
    }

    public void setLeft(Node left) {
        this.left = left;
    }

    public Node getRight() {
        return right;
    }

    public void setRight(Node right) {
        this.right = right;
    }

    @Override
    public String toString() {
        return "Node{" +
                "value=" + value +
                '}';
    }

    @Override
    public int compareTo(Node o) {
        return this.value - o.value;
    }

    //遍历二叉树
    public void preOrder() {
        System.out.println(this);
        if (this.left != null) {
            this.left.preOrder();
        }
        if (this.right != null) {
            this.right.preOrder();
        }
    }
}